package pers.xhh.frontapi.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import pers.xhh.frontapi.annotation.PassToken;
import pers.xhh.frontapi.annotation.UserLoginToken;
import pers.xhh.frontapi.common.ResultCode;
import pers.xhh.frontapi.entity.MiUserEntity;
import pers.xhh.frontapi.exception.MiException;
import pers.xhh.frontapi.service.MiUserService;
import pers.xhh.frontapi.util.LogUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MiUserEntity> threadLocal = new ThreadLocal<>();

    @Autowired
    MiUserService miUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    LogUtils.logError(getClass(), "无token,请重新登录");
                    throw new MiException(ResultCode.ERROR501.getStatus(), ResultCode.ERROR501.getMessage());
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    LogUtils.logError(getClass(), "解析token出现问题");
                    throw new MiException(ResultCode.ERROR501.getStatus(), ResultCode.ERROR501.getMessage());
                }
                // 根据id查询用户,再根据password验证
                MiUserEntity miManagerEntity = miUserService.getById(userId);
                if (miManagerEntity == null) {
                    throw new MiException(ResultCode.ERROR300.getStatus(), ResultCode.ERROR300.getMessage());
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(miManagerEntity.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new MiException(ResultCode.ERROR501.getStatus(), ResultCode.ERROR501.getMessage());
                }

                // ->无异常,线程共享用户数据
                threadLocal.set(miManagerEntity);
                return true;
            }
        }
        return true;
    }
}
